CherryPy Essentials by Sylvain Hellegouarch

CherryPy Essentials by Sylvain Hellegouarch

Author:Sylvain Hellegouarch
Language: eng
Format: epub
Publisher: Packt Publishing
Published: 2018-09-25T16:00:00+00:00


The idempotent column of the table indicates whether the request using that particular HTTP method will have the same side-effects with two consecutive identical calls.

By default CherryPy handlers reflect the path of the Request-URI and the handler matches one element of the URI, but as we have seen CherryPy's dispatcher can be changed not to look for the handler within the URI but from the request metadata such as the HTTP method used.

Let's review an example applied to the photoblog application:

import cherrypy from cherrypy.lib.cptools import accept from models import Photoblog, Album from lib.config import conf from lib.tools import find_acceptable_within class AlbumRESTService(object): exposed = True def GET(self, album_id): best = accept(['application/xml', 'application/atom+xml', 'text/json', 'text/x-json']) album = Album.fetch(album_id) if not album: raise cherrypy.NotFound() if best in ['application/xml','application/atom+xml']: cherrypy.response.headers['Content-Type'] = 'application/atom+xml' entry = album.to_atom_entry() return entry.xml() if best in ['application/json', 'text/x-json', 'text/json']: cherrypy.response.headers['Content-Type'] = 'application/json' return album.to_json() raise cherrypy.HTTPError(400, 'Bad Request') def POST(self, title, segment, author, description, content, blog_id): photoblog = Photoblog.fetch(blog_id) if not photoblog: raise cherrypy.NotFound() album = Album() album.create(photoblog, title, segment, author, description, content) cherrypy.response.status = '201 Created' cherrypy.response.headers['Location'] = '%s/album/%d' % (conf.app.base_url, album.ID) def PUT(self, album_id, title, segment, author, description, content): album = Album.fetch(album_id) if not album: raise cherrypy.NotFound() album.update(title, segment, author, description, content) def DELETE(self, album_id): album = Album.fetch(album_id) if album: album.delete() cherrypy.response.status = '204 No Content'



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.